package com.spzx.order.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private RemoteCartService remoteCartService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RemoteProductService remoteProductService;
    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    //=========查询tradeVo========================
    @Override
    public TradeVo orderTradeData() {

        /**
         * TradeVo的属性
         * totalAmount
         * orderItemList
         * tradeNo
         */
        //=====结算商品列表==========
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        //获取到购物车中勾选的商品，远程调用
        R<List<CartInfo>> cartCheckedList = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (cartCheckedList.getCode() == R.FAIL) {
            //远程调用出错的话，进行降级处理
            throw new ServiceException(cartCheckedList.getMsg());
        }
        //获取勾选的商品信息
        List<CartInfo> cartInfoList = cartCheckedList.getData();
        if (CollectionUtils.isEmpty(cartInfoList)) {
            throw new ServiceException("购物车还没添加东西呢！");
        }
        //说明是有选中的商品的
        //将List<cartInfo>-->List<orderItem>，直接将选中的购物车中的商品列表，转换成前端想要的orderItemList
        /*List<OrderItem> orderItemList = cartInfoList.stream().map((cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            orderItem.setSkuPrice(cartInfo.getSkuPrice()); //skuPrice可能还是旧价格
            return orderItem;
        })).toList();*/
        List<OrderItem> orderItemList = cartInfoList.stream().map((cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            //--------
            orderItem.setSkuPrice(cartInfo.getSkuPrice()); //skuPrice可能还是旧价格
            //--------
            return orderItem;
        })).toList();

        //=====计算总金额======
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            //bigdecimal引用数据类型，有自己的加减乘除的api
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        //=====生成订单的流水号========
        String tradeNo = generateTradeNo(userId);


        //将返回结果封装到Vo中并且返回
        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setTotalAmount(totalAmount);
        return tradeVo;
    }



    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 下订单业务逻辑：
     * 1.验证用户重复提交表单
     * 2.验证表单参数是否空
     * 3.校验价格变化
     * 4.校验库存锁定库存
     * 5.保存订单（订单表、订单项表、订单日志表）
     * 6.删除购物车选中商品
     */
    @Override
    public Long submitOrder(OrderForm orderForm) {
        //1.通过用户下单时候的流水号进行验证
        Long userId = SecurityContextHolder.getUserId();
        //获取到流水号
        //判断和删除不是原子性的。无法实现去重处理。
        String tradeNo = orderForm.getTradeNo();
        /*if(tradeNo==null){//说明

        }*/
        //生成订单的key，用以存储在redis缓存中
        String tradeNoKey = "user:tradeNo:" + userId;

        /*String script = "if  redis.call('GET',KEYS[1]==ARGV[1])  then \n" +
                "\treturn  redis.call('del',KEYS[1])\n" +
                "else return 0\n" +
                "end";*/
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then\n" +
                "\treturn redis.call('del',KEYS[1])\n" +
                "else\n" +
                "\treturn 0\n" +
                "end";
        DefaultRedisScript redisScript = new DefaultRedisScript(script);
        redisScript.setResultType(Long.class);
        Long result = (Long) redisTemplate.execute(redisScript, Arrays.asList(tradeNoKey), tradeNo);
        //验证流水号是否重复
        if (result !=1) {
            throw new ServiceException("重复提交订单");
        }
        //2.=====验证表单参数是否为空
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ServiceException("数据表单为空");
        }
        // ======验证价格是否变化
        //3.远程调用价格模块
        //getSkuPriceList批量获取数据库中商品sku的最新价格
        List<Long> skuIdList = orderItemList.stream().map(orderItem -> orderItem.getSkuId()).toList();
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (skuPriceListResult.getCode() == R.FAIL) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        //获取到skuPrice的集合
        List<SkuPrice> skuPriceList = skuPriceListResult.getData();
        //将sku价格集合转变成map存储
        Map<Long, BigDecimal> skuIdToSalePriceMap = skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));

        //
        StringBuilder stringBuilder = new StringBuilder("");
        //把表单中的价格数据遍历进行验证
        for (OrderItem orderItem : orderItemList) {
            //从数据库中获取到订单项中，sku的最新的价格
            BigDecimal bigDecimalDB = skuIdToSalePriceMap.get(orderItem.getSkuId());
            //compareTo方法，如果调用者比后边大会返回1，小于返回-1，等于返回0
            //那么如果相比较只要不等于0就说明，价格是有变动的
            if (orderItem.getSkuPrice().compareTo(bigDecimalDB) != 0) {
                stringBuilder.append("商品【" + orderItem.getSkuName() + "】价格有变动;");
            }
        }
        if (stringBuilder.length() > 0) {//说明上面的字符串拼接有变动，也就是价格有变动
            //价格有变动就对远程的购物车中的价格进行更新
            remoteCartService.updateCartPrice(userId,SecurityConstants.INNER);
            throw  new ServiceException(stringBuilder.toString());
        }

        // 4.校验库存锁定库存 TODO
        /*List<SkuLockVo> skuLockVoList = orderItemList.stream().map(item -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(item.getSkuId());
            skuLockVo.setSkuNum(item.getSkuNum());
            return skuLockVo;
        }).collect(Collectors.toList());
        String checkAndLockResult = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER).getData();
        if(StringUtils.isNotEmpty(checkAndLockResult)) {
            throw new ServiceException(checkAndLockResult);
        }*/
        List<SkuLockVo> skuLockList = orderItemList.stream().map(item -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(item.getSkuId());
            skuLockVo.setSkuNum(item.getSkuNum());
            return skuLockVo;
        }).toList();
        String data = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockList).getData();
        if(!StringUtils.isEmpty(data)){
            throw new ServiceException(data);
        }

        // 5.保存订单（订单表、订单项表、订单日志表）
        //保存订单到三张表(order_info、order_item、)
        Long orderId=null;
        try {
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        // 6.删除购物车选中商品
        //远程调用购物车的删除商品方法
        remoteCartService.deleteCartCheckedList(userId,SecurityConstants.INNER);


        return orderId;
    }

    /**
     * 保存订单
     * @param orderForm
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Long saveOrder(OrderForm orderForm){
        //获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();

        //1.保存订单表
        OrderInfo orderInfo = new OrderInfo();

        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(SecurityContextHolder.getUserName());
        orderInfo.setRemark(orderForm.getRemark());
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount); //实付总价格(含优惠卷和运费)
        orderInfo.setCouponAmount(new BigDecimal(0)); //优惠卷
        orderInfo.setOriginalTotalAmount(totalAmount); //商品总价格
        orderInfo.setFeightFee(orderForm.getFeightFee()); //运费
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0);

        orderInfoMapper.insert(orderInfo); //主键回填

        //2.保存订单项数据
        for (OrderItem orderItem : orderItemList) {

            orderItem.setOrderId(orderInfo.getId()); //外键

            orderItemMapper.insert(orderItem);
        }

        //3.保存订单日志数据
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");
        orderLogMapper.insert(orderLog);
        Long orderInfoId = orderInfo.getId();
        return orderInfoId;
    }
}